﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using WmsApp.Exceptions;
using WmsApp.Security;
using WmsApp.StaticData;
using WmsApp.Style;
using WmsApp.Window;
using WmsApp.WindowControl;

namespace WmsApp
{
    public partial class FormMain : XtraForm
    {
        public const string HeadText = "仓库管理系统WMS --------欢迎用户：{0} 登录仓库管理系统......";
        private static FormMain _formMainInstance;

        private FormWelcome _formWelcome;

        public FormMain()
        {
            _formMainInstance = this;

            InitializeComponent();

            InitStyleAndForms();

            //退出系统的时候开启更新检查
            Application.ThreadExit += (sender, e) =>
                                          {
                                              try
                                              {
                                                  Process.Start("WmsRunStart.exe", "update");
                                                  DeleteExpiredStyleFiles();
                                              }
                                              catch (Exception exception)
                                              {
                                                  XtraMessageBox.Show("启动更新程序失败！" + exception.Message, "错误",
                                                                      MessageBoxButtons.OK,
                                                                      MessageBoxIcon.Error);
                                              }
                                          };
           
        }

        private string GetAsseblyVersion()
        {
            return Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }

        private void DeleteExpiredStyleFiles()
        {
            try
            {
                if (UserSession.CurrentUser == null)
                    return;

                string dir = Application.StartupPath + "\\Layout\\" + UserSession.CurrentUser.USERID;
                if (Directory.Exists(dir))
                {
                    string[] files = Directory.GetFiles(dir);
                    foreach (var file in files)
                    {
                        if (!file.EndsWith(GetAsseblyVersion() + ".layout"))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
// ReSharper disable EmptyGeneralCatchClause
            catch {}
// ReSharper restore EmptyGeneralCatchClause
        }

        public static FormMain FormMainInstance
        {
            get { return _formMainInstance; }
        }

        private void InitStyleAndForms()
        {
            ShowWelcome();

            //外观控制
            ILookAndFeelController lookAndFeelController = new LookAndFeelController();
            lookAndFeelController.LoadLookAndFeelMenu(barSubItemStyle, defaultLookAndFeel);
        }

        private void ShowWelcome()
        {
            _formWelcome = MainFormControl.GenerateFormFree<FormWelcome>();
            AddOwnedForm(_formWelcome);
            _formWelcome.MdiParent = this;

            FormMainInstance._formWelcome.Show();
            FormMainInstance._formWelcome.Activate();
        }

        public void ShowChildrenForm<TF>()
            where TF : BaseForm, new()
        {
            MainFormControl.GenerateForm<TF>(this);
        }

        public void UserManagerVisual(bool b)
        {
            barSubItemUserManage.Enabled = b;
            barButtonItemPublish.Enabled = b;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var form = new LoginForm();
            form.ShowDialog(this);
            if (form.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Application.Exit();
            }
        }

        internal void CloseAllChild()
        {
            foreach (var form in MdiChildren)
            {
                if (form is FormWelcome)
                {
                    continue;
                }
                form.Close();
            }
        }

        #region MenuEvent

        private void BarSubItemUserManageItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormUserManage>(this);
        }

        private void BarSubItemChangePassItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                PasswordService.ChangePassword();
            }
            catch (Exception ex)
            {
                ExceptionHandler.ShowException(ex);
            }
        }

        private void BarSubItemQuitItemClick(object sender, ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void BarSubItemProviderManageItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormProvider>(this);
        }

        private void BarSubItemGoodsCodeTypeItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormGoodsCodeType>(this);
        }

        private void BarSubItemStoreTypeItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormStoreType>(this);
        }

        private void BarSubItemInItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormIn>(this);
        }

        private void BarSubItemOutItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormOut>(this);
        }

        private void BarSubItemStoreQueryItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormStoreQuery>(this);
        }

        private void BarSubItemAboutItemClick(object sender, ItemClickEventArgs e)
        {
            var form = new AboutBox();
            form.ShowDialog();
        }

        private void BarSubItemUnitItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormUnit>(this);
        }

        private void BarButtonItemInOutStoreTypeItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormInOutStoreType>(this);
        }

        private void BarButtonItemReLoginItemClick(object sender, ItemClickEventArgs e)
        {
            var form = new LoginForm();
            form.ShowDialog();
        }

        private void BarButtonItemPayTypeItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormPayType>(this);
        }

        private void BarButtonItemPayApplyBillItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormPayApplyBill>(this);
        }

        private void BarButtonItemPublishItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormPublish>(this);
        }

        private void BarButtonItemInvoiceBillItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormInvoice>(this);
        }

        private void BarButtonItemBorrowRepairItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormBorrowRepairQuery>(this);
        }

        private void BarButtonItemRefreshCacheItemClick(object sender, ItemClickEventArgs e)
        {
            StaticObjects.RefreshStaticObjects();
            var subject = GoodsCodeTypeSubjectFactory.GetGoodsCodeTypeSubject();
            subject.Nofify();
        }

        private void BarButtonItemInvoiceInStoreItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormInInvoice>(this);
        }

        private void BarButtonItemStockTackingItemClick(object sender, ItemClickEventArgs e)
        {
            MainFormControl.GenerateForm<FormStockTacking>(this);
        }
        #endregion
    }
}